/**
 * 权限声明：
 */
package com.handy.webwork.config;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.handy.webwork.action.ActionMapping;
import com.handy.webwork.action.ActionResult;
import com.handy.webwork.plugin.PluginBean;
import com.handy.webwork.view.MessageResource;

/**
 * 读取配置文件信息到Configuration中。 <br>
 * 使用apache-commons-configuration做解析。 <br>
 * 导入所有配置文件: <br>
 * 1、导入handy.properties，判断是否有共用资源文件的名称与路径，有则导入到MessageResource中; <br>
 * 2、导入freemarker.properties; <br>
 * 3、导入classpath下所有以handy_plugin为前缀的xml文件，
 *   根据xml中定义的actionPath与messagePath导入插件的action定义与资源; <br>
 * 
 * @author rocken.zeng@gmail.com
 * 
 */
public class ConfigurationManager {

	public ConfigurationManager() {
		removeAll();
	}

	/**
	 * 导入配置文件.
	 */
	public void loadConfiguration() {
		loadProperties();
		loadFreemarker();
		loadHandyXml();
		loadPlugin();
	}

	/**
	 * 解析handy.xml,装载interceptor,action,forward.
	 */
	private void loadHandyXml() {
		//判断是否存在handy.xml文件，如果没有则返回。
		if (!isHandyExist()) return;
		try {
			LinkedList<String> files = parseInclude();
			for (String fileName : files) {
				XMLConfiguration config = new XMLConfiguration(fileName);// 取指定的配置文件到XMLConfiguration中。
				String packageName = (String) config
						.getProperty("package[@name]");// 包名
				loadInterceptor(config, packageName);// 装载拦截器
				loadAction(config, packageName,null);// 装载控制器
				loadForward(config, packageName,null);// 装载转向器
			}
			if (log.isDebugEnabled()) {
				log.info("Configuration:===============");
				for (String fileName : files) {
					XMLConfiguration config = new XMLConfiguration(fileName);// 取指定的配置文件到XMLConfiguration中。
					String packageName = (String) config
							.getProperty("package[@name]");// 包名
					log.info("filename:" + fileName);
					log.info("packageName:" + packageName);
				}
				log.info("Configuration end:===========");
			}
		} catch (ConfigurationException cex) {
			log.error(cex.getMessage());
		}
	}

	
	/**
	 * 处理include元素。
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private LinkedList<String> parseInclude() {
		LinkedList<String> files = new LinkedList<String>();
		files.add("handy.xml");
		try {
			XMLConfiguration config = new XMLConfiguration("handy.xml");// 取指定的配置文件到XMLConfiguration中。
			// 解析include标签
			Object includeProp = config.getProperty("include[@file]");// 包下所有include的file属性
			if (includeProp instanceof Collection) {
				Collection<String> includes = (Collection<String>) includeProp;
				for (String include : includes) {
					files.add(include);
				}
			} else {
				if (null != includeProp) {
					files.add((String) includeProp);
				}
			}
		} catch (ConfigurationException cex) {
			log.error(cex.getMessage());
		}
		return files;
	}

	/**
	 * 处理插件配置文件。
	 */
	private void loadPlugin() {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		LinkedList<String> pluginFiles = new LinkedList<String>();//插件的配置文件
		LinkedList<String> scriptFiles = new LinkedList<String>();//所有脚本文件
		HashMap<String,String> hm = new HashMap<String,String>();//将所有xml,properties文件分目录存储
		Set<String> allFiles = new HashSet<String>();
		//导入classpath下所有xml,properties,js文件
		getFiles(loader.getResource(""));
		allFiles.addAll(classesFiles);
		allFiles.addAll(getJarFiles(loader.getResource("../lib")));
		
		for (String s : allFiles) {
			if (s.toUpperCase().startsWith("META-INF")) continue;
			//将插件定义文件与其它文件分开存储
			if (s.toUpperCase().indexOf("HANDY_PLUGIN_") != -1
					&& s.toUpperCase().endsWith("XML")) {
				//将插件定义文件存储到pluginFiles
				pluginFiles.add(s);
				if (log.isDebugEnabled()){
					log.info(s);
				}
			}else if (s.toUpperCase().endsWith(".JS")){//脚本文件
				//分析文件名
				String jsFilename = s.substring(s.lastIndexOf('/')+1);
				if (jsFilename.startsWith("_")){
					scriptFiles.add(s);
				}
			} else if (s.indexOf("/") > 0) {
				//以文件的路径为键值分开存储
				String a = s.toUpperCase().substring(0,
						s.toUpperCase().lastIndexOf('/'));
				if (hm.get(a) == null) {
					hm.put(a, s);
				} else {
					hm.put(a, hm.get(a) + ";" + s);
				}
				if (log.isDebugEnabled()) {
					log.info(s);
				}
			}
		}
		
		HandyConfiguration.putScriptFiles(scriptFiles);
		scriptFiles.clear();
		
		OrderList comparator=new OrderList();
		Collections.sort(pluginFiles, comparator);//将pluginFiles中的plugin根据displayOrder排序
		
		try {
			//解析所有的plugin.xml
			for (String fileName : pluginFiles) {
				XMLConfiguration config = new XMLConfiguration(fileName);
				PluginBean plugin = new PluginBean();
				plugin.setName( (String)config.getProperty("plugin[@name]"));
				plugin.setEntry( (String)config.getProperty("plugin.entry"));
				
				plugin.setActionPath( (String)config.getProperty("plugin.actionPath"));
				if (null == plugin.getActionPath() || "".equals(plugin.getActionPath())){
					//plugin.setActionPath(plugin.getName()+"Actions");
					plugin.setActionPath(plugin.getName());//默认插件action配置文件在“插件名”目录
				}else if(plugin.getActionPath().endsWith("/")){
					plugin.setActionPath(plugin.getActionPath().substring(0, plugin.getActionPath().length()-1));
				}
				
				plugin.setMessagePath( (String)config.getProperty("plugin.messagePath"));	
				if (null == plugin.getMessagePath() || "".equals(plugin.getMessagePath())){
					//plugin.setMessagePath(plugin.getName()+"Message");
					plugin.setMessagePath(plugin.getName());//默认插件action配置文件在“插件名”目录
				}else if (plugin.getMessagePath().endsWith("/")){
					plugin.setMessagePath(plugin.getMessagePath().substring(0, plugin.getMessagePath().length()-1));
				}
				plugin.setUrl( (String)config.getProperty("plugin.url"));
				plugin.setLogo( (String)config.getProperty("plugin.logo"));
				plugin.setTitle( (String)config.getProperty("plugin.title"));
				plugin.setDesp( (String)config.getProperty("plugin.desp"));
				plugin.setDisplayOrder( (String)config.getProperty("plugin.displayOrder"));
				
				plugin.setAccess( (String)config.getProperty("plugin.access"));
				if (null == plugin.getAccess() || "".equals(plugin.getAccess())){
					plugin.setAccess("true");
				}
				
				plugin.setDataSource((String)config.getProperty("plugin.dataSource"));
				
				String root = (String)config.getProperty("plugin.root");
				
				if(root == null || "".equals(root) || "//".equals(root) ){
					//如果不定义或定义为'//'则访问时会自动加上插件名，访问的url如下：http://ip/%context%/插件名/xx.action
					root = plugin.getName();
				}else if("/".equals(root)){
					//如果定义为'/'则访问时不会加上插件的名称，访问的url如下：http://ip/%context%/xx.action
					root = "";
				}else if (root.startsWith("/")){
					//如果定义为'/自命名，访问的url如下:http://ip/%context%/自命名/xx.action
					root = root.substring(1);
					while (root.endsWith("/")){
						root = root.substring(0, root.lastIndexOf('/'));
					}
				}
				plugin.setRoot (root);
				
				//该插件不充许访问，action配置与resource配置不读取。
				if (!Boolean.valueOf(plugin.getAccess())){
					if (log.isInfoEnabled()){
						log.info("["+plugin.getName()+"]插件不充许访问，配置文件不导入。");
					}
					continue;
				}
				
				HandyConfiguration.putPlugins(plugin); //加入插件集合
				
				//取该插件下ActionPath目录下的所有XML文件，action定义。
				String actionPathFiles =  hm.get(plugin.getActionPath().toUpperCase());
//				log.info(actionPathFiles);
				if (null != actionPathFiles && !"".equals(actionPathFiles)) {
					String[] arr = actionPathFiles.split(";");
					for (String file : arr) {
						if (!file.toUpperCase().endsWith("XML")) continue;
						config = new XMLConfiguration(file);
						String packageName = (String) config
								.getProperty("package[@name]");// 包名
						loadInterceptor(config, packageName);// 装载拦截器
						loadAction(config, packageName, plugin);// 装载控制器
						loadForward(config, packageName, plugin);// 装载转向器
						plugin.getFiles().add(file);
					}
				}

				//取该插件下MessagePath目录下的所有properties文件，文字资源。
				String messagePathFiles = hm.get(plugin.getMessagePath().toUpperCase());
					
				if (null != messagePathFiles && !"".equals(messagePathFiles)){
					String[] arr = messagePathFiles.split(";");
					for(String  file : arr){
						if (!file.toUpperCase().endsWith("PROPERTIES")) continue;
						loadMessageRessource(plugin.getName(),file);
						plugin.getFiles().add(file);
					}
				}
			}
		} catch (ConfigurationException cex) {
			log.error(cex.getMessage());
		}
		
		//释放临时资源
		classesFiles.clear();
		pluginFiles.clear();
		hm.clear();
	}

	/**
	 * 遍历指定jar包的所有文件
	 * @param url
	 * @return
	 */
	private List<String> getJarFiles(URL url) {
		List<String> list = new ArrayList<String>();
		File file = new File(url.getFile());
		String[] files = file.list();
		for (String jarFileName : files) {
			if (jarFileName.toUpperCase().endsWith("JAR")) {
				try {
					JarFile jarFile = new JarFile(url.getFile() + jarFileName);
					Enumeration<JarEntry> inJarFiles = jarFile.entries();
					while (inJarFiles.hasMoreElements()) {
						JarEntry entry = (JarEntry) inJarFiles.nextElement();
						String name = entry.getName();
						//将.xml,.properties文件检索出来
						if (name.toUpperCase().endsWith(".XML")
								|| name.toUpperCase().endsWith(".PROPERTIES") 
								|| name.toUpperCase().endsWith(".JS")) {
//							log.info(name);
							list.add(name);
						}
					}
				} catch (IOException e) {
					log.error(e.getMessage());
				}
			}
		}
		return list;
	}

	/**
	 * 遍历指定url下的所有文件
	 * @param root
	 * @return
	 */
	private void getFiles(URL root){
		getFiles(root,null);
	}
	
	private List<String> classesFiles = new ArrayList<String>();//classes下所有文件列表
	
	/**
	 * 遍历指定url下的所有文件,将所需文件选出。
	 * 
	 * @param root
	 * @param url
	 * @return
	 */
	@SuppressWarnings("deprecation")
	private void getFiles(URL root, URL url) {
		if (url == null)
			url = root;
		File file = new File(url.getFile());
		if (file.isDirectory()) {
			File[] f = file.listFiles();
			for (int i = 0; i < f.length; i++) {
				try {
					URL fileURL = f[i].toURI().toURL();
					//将.xml,.properties文件检索出来
					if (fileURL.getFile().toUpperCase().endsWith(".XML") 
							|| fileURL.getFile().toUpperCase().endsWith(".PROPERTIES") 
							|| fileURL.getFile().toUpperCase().endsWith(".JS")) {
						classesFiles.add(f[i].toURI().toURL().getFile().replaceAll(
								root.getFile(), ""));
					}
					getFiles(root, fileURL);
				} catch (MalformedURLException e) {
					log.error(e.getMessage());
				}
			}
		}
	}
	
	/**
	 * 判断handy.xml是否存在
	 * @return
	 */
	private boolean isHandyExist(){
		String handy = "handy.xml";
		File file = new File(Thread.currentThread().getContextClassLoader().getResource("").getFile());
		String[] files = file.list();
		boolean exist = false;
		for (String _file:files){
			if (handy.equalsIgnoreCase(_file)) {
				exist =  true;
				break;
			}
		}
		return exist;
	}

	 
	/**
	 * 解析action
	 * 
	 * @param config
	 * @param packageName
	 */
	@SuppressWarnings("unchecked")
	private void loadAction(XMLConfiguration config, String packageName, PluginBean plugin) {
		int actionCount = 0;// action计数器
		int resultCount = 0;// result计数器
		String actionName = "";// 控制器名称
		String actionClass = "";// 控制器实现类
		String resultName = "";// 结果处理名
		String resultType = "";// 结果处理类型，分为freemarker,forward,redirect
		String contentType = "";//页面输出类型
		String resultValue = "";// 结果处理显示地址
		String viewPath = (String)config.getProperty("package.viewPath");
		if(viewPath==null) viewPath = "";
		
		String pluginName = "";
		String pluginRoot = "";
		if (plugin != null){
			pluginName = plugin.getName();
			pluginRoot = plugin.getRoot();
		}
		
		Object actionProp = config.getProperty("package.action[@name]");// 包下所有action的名称
		if (actionProp instanceof Collection) {
			actionCount = ((Collection) actionProp).size();// 包内action的数量
		} else {
			if (null != actionProp) {
				actionCount = 1;
			} else {
				return;
			}
		}

		for (int i = 0; i < actionCount; i++) {// 循环装载action
			actionName = (String) config.getProperty("package.action(" + i
					+ ")[@name]");

			// 如果没有定义控制器名，跳过。
			if (null == actionName || "".equals(actionName)) {
				log.error("有未命名的控制器action,请为该控制器命名.");
				log.error("忽略该控制器.");
				continue;
			}

			actionClass = (String) config.getProperty("package.action(" + i
					+ ")[@class]");

			HashMap<String, ActionResult> actionResults = new HashMap<String, ActionResult>();
			List results = config.getList("package.action(" + i + ").result");// 该控制器下所有结果处理方式
			resultCount = results.size();// 该控制器内result的数量
			for (int j = 0; j < resultCount; j++) {// 循环装载action的result
				resultName = (String) config.getProperty("package.action(" + i
						+ ").result(" + j + ")[@name]");
				resultType = (String) config.getProperty("package.action(" + i
						+ ").result(" + j + ")[@type]");
				contentType = (String) config.getProperty("package.action(" + i
						+ ").result(" + j + ")[@contentType]");
				resultValue = (String) config.getProperty("package.action(" + i
						+ ").result(" + j + ")");
				//返回值的处理: 解析视图地址中的$viewPath
				if(!"".equals(viewPath)){
					resultValue = resultValue.replace("$viewPath",viewPath );
				}
				//返回值的处理: 返回FORWARD或REDIRECT的处理,解析地址中的$pluginRoot
				if(resultType!=null && !"".equals(resultType)){
					if(resultType.toUpperCase().equals(HandyConfiguration.RESULT_FORWARD) || 
							resultType.toUpperCase().equals(HandyConfiguration.RESULT_REDIRECT)){
						resultValue = resultValue.replace("$pluginRoot",pluginRoot );
					}
				}
				// 装载控制器下的结果处理MAP
				resultName = resultName.toUpperCase();
				if (null == actionResults.get(resultName)) {
					actionResults.put(resultName, new ActionResult());
					ActionResult result = actionResults.get(resultName);
					result.setResultName(resultName);
					result.setResultType(resultType);
					result.setContentType(contentType);
					result.setResultValue(resultValue);
				} else {
					log.error("控制器" + actionName + "下" + resultName
							+ "重复定义，同控制器下的同名返回结果无法生效！");
				}
			}
			// 装载控制器类，key为控制器名。
			if( "".equals(pluginRoot) ){
				actionName = actionName.toUpperCase();
			}
			else{
				actionName = pluginRoot.toUpperCase()+"/"+actionName.toUpperCase();
			}

			if (null == HandyConfiguration.actionMappings(actionName)) {
				HandyConfiguration.putActionMappings(actionName,
						new ActionMapping());
				ActionMapping am = HandyConfiguration
						.actionMappings(actionName);
				am.setActionName(actionName);
				am.setActionClass(actionClass);
				am.setActionPackage(packageName);
				am.setActionResults(actionResults);
				am.setPluginRoot(pluginRoot);
				am.setPluginName(pluginName);
			} else {
				log.error("控制器" + actionName + "重复定义，该控制器下的同名控制器无法生效！");
			}		
		}
		
		if (log.isDebugEnabled()) {
			log.info("=========== loadAction start ===========");
			// 打印所有action
			HandyConfiguration.getInstance().printActionMappings();
			log.info("=========== loadAction end   ===========");
		}
	}

	/**
	 * 解析forward <br>
	 * <forward name="test" type="freemarker" contentType="text/html">/WEB-INF/templates/test.ftl</forward>
	 * <br>
	 * 象这样的转向器可以看做是这样一个action <br>
	 * 注：contentType可以不定义，默认为text/html。<br>
	 * <action name="test" class="com.handy.action.BaseAction"> <br>
	 * <result name="success" type="freemarker" contentType="text/html">/WEB-INF/templates/test.ftl</result>
	 * <br>
	 * </action>
	 * 
	 * @param config
	 * @param packageName
	 */
	@SuppressWarnings("unchecked")
	private void loadForward(XMLConfiguration config, String packageName, PluginBean plugin) {
		int forwardCount = 0;// forward计数器
		String actionName = "";// 控制器名称
		String actionClass = "com.handy.actoin.Action";// 控制器处理类
		String resultName = "";// 返回名称
		String resultType = "";// 结果处理类型，分为freemarker,forward,redirect
		String contentType = "";
		String resultValue = "";// 结果处理显示地址
		String viewPath = (String)config.getProperty("package.viewPath");
		if(viewPath==null) viewPath = "";
		
		String pluginName = "";
		String pluginRoot = "";
		if (plugin != null){
			pluginName = plugin.getName();
			pluginRoot = plugin.getRoot();
		}
		
		Object forwardProp = config.getProperty("package.forward[@name]");// 包下所有forward的名称

		if (forwardProp instanceof Collection) {
			forwardCount = ((Collection) forwardProp).size();// 包内forward的数量
		} else {
			if (null != forwardProp) {
				forwardCount = 1;
			} else {
				return;
			}
		}

		for (int i = 0; i < forwardCount; i++) {// 循环装载forward
			actionName = (String) config.getProperty("package.forward(" + i
					+ ")[@name]");

			// 如果没有定义跳转器名，跳过。
			if (null == actionName || "".equals(actionName)) {
				log.error("没有为该跳转器命名，忽略该跳转器，请为该跳转器命名。");
				continue;
			}

			resultName = "SUCCESS";
			resultType = (String) config.getProperty("package.forward(" + i
					+ ").[@type]");
			contentType = (String) config.getProperty("package.forward(" + i
					+ ").[@contentType]");
			resultValue = (String) config.getProperty("package.forward(" + i
					+ ")");
			if(!"".equals(viewPath)){
				resultValue = resultValue.replace("$viewPath",viewPath );
			}
			
			ActionResult result = new ActionResult();
			result.setResultName(resultName);
			result.setResultType(resultType);
			result.setContentType(contentType);
			result.setResultValue(resultValue);
			HashMap<String, ActionResult> actionResults = new HashMap<String, ActionResult>();
			actionResults.put(resultName, result);
			
			// 装载控制器类，key为控制器名。
			if( "".equals(pluginRoot) ){
				actionName = actionName.toUpperCase();
			}
			else{
				actionName = pluginRoot.toUpperCase()+"/"+actionName.toUpperCase();
			}
			if (null == HandyConfiguration.actionMappings(actionName)) {
				HandyConfiguration.putActionMappings(actionName,
						new ActionMapping());
				ActionMapping am = HandyConfiguration
						.actionMappings(actionName);
				am.setActionName(actionName);
				am.setActionClass(actionClass);
				am.setActionPackage(packageName);
				am.setActionResults(actionResults);
				am.setStyle(HandyConfiguration.ACTION_SYTLE_FORWARD);
				am.setPluginRoot(pluginRoot);
				am.setPluginName(pluginName);
			} else {
				log.error("跳转器(控制器)" + actionName
						+ "重复定义，该跳转器(控制器)下的同名跳转器(控制器)无法生效！");
			}
		}
		if (log.isDebugEnabled()) {
			log.debug("=========== loadForward start ===========");
			// 打印所有action
			HandyConfiguration.getInstance().printActionMappings();
			log.debug("=========== loadForward end   ===========");
		}
	}

	/**
	 * 解析interceptor
	 * 
	 * @param config
	 * @param packageName
	 */
	@SuppressWarnings("unchecked")
	private void loadInterceptor(XMLConfiguration config, String packageName) {
		int interceptorCount = 0;// interceptor计数器
		int resultCount = 0;// result计数器
		String interceptorName = "";// 拦截器名称
		String interceptorClass = "";// 拦截器实现类
		String resultName = "";// 结果处理名
		String resultType = "";// 结果处理类型，分为freemarker,forward,redirect
		String contentType = "";
		String resultValue = "";// 结果处理显示地址
		String viewPath = (String)config.getProperty("package.viewPath");
		if(viewPath==null) viewPath = "";

		Object interceptorProp = config
				.getProperty("package.interceptor[@name]");// 包下所有interceptor的名称

		if (interceptorProp instanceof Collection) {
			interceptorCount = ((Collection) interceptorProp).size();// 包内action的数量
		} else {
			if (null != interceptorProp) {
				interceptorCount = 1;
			} else {
				return;
			}
		}

		if (null == HandyConfiguration.interceptorMappings(packageName)) {
			HandyConfiguration.putInterceptorMappings(packageName,
					new LinkedList<ActionMapping>());
		}

		LinkedList<ActionMapping> interceptors = HandyConfiguration
				.interceptorMappings(packageName);

		for (int i = 0; i < interceptorCount; i++) {// 循环装载interceptor
			interceptorName = (String) config
					.getProperty("package.interceptor(" + i + ")[@name]");
			// 如果没有定义拦截器名，跳过。
			if (null == interceptorName || "".equals(interceptorName)) {
				log.error("没有为该拦截器命名，忽略该拦截器，请为该拦截器命名。");
				continue;
			}
			// 检查interceptors是否已有同名的interceptor，如果已经存在，则跳过。
			for (ActionMapping interceptor : interceptors) {
				if (interceptorName.equalsIgnoreCase(interceptor.getActionName()))
					continue;
			}
			// 拦截器实现类
			interceptorClass = (String) config
					.getProperty("package.interceptor(" + i + ")[@class]");

			// 拦截器返回处理
			HashMap<String, ActionResult> actionResults = new HashMap<String, ActionResult>();
			List results = config.getList("package.interceptor(" + i
					+ ").result");// 该控制器下所有结果处理方式
			resultCount = results.size();// 该控制器内result的数量
			for (int j = 0; j < resultCount; j++) {// 循环装载action的result
				resultName = (String) config.getProperty("package.interceptor("
						+ i + ").result(" + j + ")[@name]");
				resultType = (String) config.getProperty("package.interceptor("
						+ i + ").result(" + j + ")[@type]");
				contentType = (String) config.getProperty("package.interceptor("
						+ i + ").result(" + j + ")[@contentType]");
				resultValue = (String) config
						.getProperty("package.interceptor(" + i + ").result("
								+ j + ")");
				if(!"".equals(viewPath))
					resultValue = resultValue.replace("$viewPath",viewPath );
				// 装载控制器下的结果处理MAP
				resultName = resultName.toUpperCase();
				if (null == actionResults.get(resultName)) {
					actionResults.put(resultName, new ActionResult());
					ActionResult result = actionResults.get(resultName);
					result.setResultName(resultName);
					result.setResultType(resultType);
					result.setContentType(contentType);
					result.setResultValue(resultValue);
				} else {
					log.error("拦截器[" + interceptorName + "]下[" + resultName
							+ "]重复定义，同控制器下的同名返回结果无法生效！");
				}
			}
			// 生成ActionInterceptor类
			ActionMapping interceptor = new ActionMapping();
			interceptor.setStyle(HandyConfiguration.ACTION_SYTLE_INTERCEPTOR);
			interceptor.setActionName(interceptorName);
			interceptor.setActionClass(interceptorClass);
			interceptor.setActionResults(actionResults);
			interceptor.setPluginRoot("");
			// 装载
			interceptors.add(interceptor);
		}
		if (log.isDebugEnabled()) {// 输出
			log.info("=========== InterceptorMappings start ===========");
			// 打印所有interceptor
			HandyConfiguration.getInstance().printInterceptorMappings();
			log.info("=========== InterceptorMappings end   ===========");
		}
	}

	/**
	 * 导入配置文件handy.properties.
	 */
	@SuppressWarnings("unchecked")
	private void loadProperties() {
		try {
			PropertiesConfiguration config = new PropertiesConfiguration(
					"handy.properties");
			Iterator<String> iter = config.getKeys();
			while (iter.hasNext()) {
				String key = iter.next();
				HandyConfiguration.putProperties(key.toUpperCase(), config
						.getString(key));
			}
		} catch (ConfigurationException e) {
			log.error(e.getMessage());
		}
		// 设置默认编码
		if (null == HandyConfiguration
				.properties(HandyConfiguration.PROP_ENCODING)) {
			HandyConfiguration.putProperties(HandyConfiguration.PROP_ENCODING,
					"utf-8");
		}
		// 设置默认处理后缀为action
		if (null == HandyConfiguration
				.properties(HandyConfiguration.PROP_SUFFIX)) {
			HandyConfiguration.putProperties(HandyConfiguration.PROP_SUFFIX,
					"action");
		}
		// 设置默认自动处理form参数
		if (null == HandyConfiguration
				.properties(HandyConfiguration.PROP_AUTODEALWITHFORM)) {
			HandyConfiguration.putProperties(
					HandyConfiguration.PROP_AUTODEALWITHFORM, "true");
		}
		if (log.isDebugEnabled()) {// 输出
			log.info("=========== handy.properties start ===========");
			HandyConfiguration.getInstance().printProperties();
			log.info("=========== handy.properties end   ===========");
		}
		
		// 从系统配置中取资源文件路径
		String messageFile = HandyConfiguration
				.properties(HandyConfiguration.PROP_MESSAGERESSOURCE);
		if (null != messageFile && !"".equals(messageFile)){
			loadMessageRessource(messageFile);
		}
	}

	/**
	 * 导入公共资源文件。
	 */
	private void loadMessageRessource(String messageFile) {
		loadMessageRessource("",messageFile);
	}
	
	/**
	 * 导入资源文件。
	 */
	@SuppressWarnings("unchecked")
	private void loadMessageRessource(String bundle,String messageFile) {
		if (null == messageFile || "".equals(messageFile)){
			log.error("指定的资源文件名不能为空");
			return;// 没有指定,跳过.
		}
			
		try {
			PropertiesConfiguration config = new PropertiesConfiguration(
					messageFile);
			Iterator<String> iter = config.getKeys();
			while (iter.hasNext()) {
				String key = iter.next();
				if (bundle!=null && !"".equals(bundle)){
					MessageResource.putText(bundle,key.toUpperCase(), config
							.getString(key));
					
				}else
				{
					MessageResource.putText(key.toUpperCase(), config
							.getString(key));
				}
				
			}
		} catch (ConfigurationException e) {
			log.error(e.getMessage());
		}
		if (log.isDebugEnabled()) {// 输出
			log.info("=========== messageRessource start ===========");
			MessageResource.getInstance().print();
			log.info("=========== messageRessource end   ===========");
		}
	}

	/**
	 * 导入配置文件handy.properties.
	 */
	@SuppressWarnings("unchecked")
	private void loadFreemarker() {
		try {
			PropertiesConfiguration config = new PropertiesConfiguration(
					"freemarker.properties");
			Iterator<String> iter = config.getKeys();
			while (iter.hasNext()) {
				String key = iter.next();
				HandyConfiguration.putFreemarkers(key.toUpperCase(), config
						.getString(key));
			}
		} catch (ConfigurationException e) {
			log.error(e.getMessage());
		}
		if (log.isDebugEnabled()) {// 输出
			log.debug("=========== freemarker.properties start ===========");
			HandyConfiguration.getInstance().printFreemarker();
			log.debug("=========== freemarker.properties end   ===========");
		}

	}
	
	public void loadRootPath(String rootPath){
		HandyConfiguration.putRootPath(rootPath);
	}

	/**
	 * 清空所有参数。
	 */
	public void removeAll() {
		HandyConfiguration.getInstance().clear();
		MessageResource.getInstance().clear();
	}

	

	private static Log log = LogFactory.getLog(ConfigurationManager.class);

	
	class OrderList implements Comparator<Object>{

		 public int compare(Object arg0, Object arg1) {
			 String order0,order1;
			 int flag = -1;
			 try {
					XMLConfiguration config0 = new XMLConfiguration((String)arg0);
					XMLConfiguration config1 = new XMLConfiguration((String)arg1);
					
					order0 = (String)config0.getProperty("plugin.displayOrder");
					order1 = (String)config1.getProperty("plugin.displayOrder");
					flag = order0.compareTo(order1);
					
				} catch (ConfigurationException e) {
					log.error(e.getMessage());
				}
				return flag;
		}
	}
}

